import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import Inspector from "vite-plugin-vue-inspector";
import vueJsx from "@vitejs/plugin-vue-jsx";
import path from "path";
import os from "os";
// 自动引入组件，并按需引入组件的样式。在.vue模版语法中有效 在.tsx中 <el-button type='primary'> 无效
import AutoImport from "unplugin-auto-import/vite"; // 自动导入
import Components from "unplugin-vue-components/vite"; // 组件注册
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
// 手动导入组件 例如： import { ElButton } from 'element-plus' 为了在.tsx中正常使用组件
import ElementPlus from "unplugin-element-plus/vite";
import Icons from "unplugin-icons/vite"; // icon相关
import IconsResolver from "unplugin-icons/resolver"; // icon相关
import { svgBuilder } from "./src/plugins/svgBuilder.js";

function getNetWorkIp() {
  let needHost = "";
  try {
    let network = os.networkInterfaces();
    for (const dev in network) {
      let iface = network[dev];
      for (let i = 0; i < iface.length; i++) {
        const alias = iface[i];
        if (
          alias.family === "IPv4" &&
          alias.address !== "127.0.0.1" &&
          !alias.internal
        ) {
          needHost = alias.address;
        }
      }
    }
  } catch (error) {
    needHost = "localhost";
  }
  return needHost;
}
const IP = getNetWorkIp();
console.log("Ip", IP);

export default ({ mode }: any) => {
  const config = loadEnv(mode, process.cwd());
  const isProduction = config.VITE_ENV !== "development";
  return defineConfig({
    base: config.VITE_ENV === "development" ? "/" : "./",
    productionSourceMap: !isProduction,
    resolve: {
      alias: {
        "~/": `${path.resolve(__dirname, "src")}/`,
        "@": path.resolve(__dirname, "src"),
        "@assets": path.resolve(__dirname, "src/assets"),
        "@components": path.resolve(__dirname, "src/components"),
        "@images": path.resolve(__dirname, "src/assets/images"),
        "@views": path.resolve(__dirname, "src/views"),
        "@store": path.resolve(__dirname, "src/store"),
      },
    },
    // 配置sass
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/components/ElementPlus/theme-chalk/index.scss" as *; @use "@/assets/scss/index.scss" as *;
        `,
        },
      },
    },
    build: {
      outDir: "dist",
      assetsDir: "assets",
      sourcemap: false,
      minify: "terser",
      chunkSizeWarningLimit: 2 * 1024,
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
        output: {
          comments: true,
        },
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
          chunkFileNames: (chunkInfo) => {
            const facadeModuleId = chunkInfo.facadeModuleId
              ? chunkInfo.facadeModuleId.split("/")
              : [];
            const fileName =
              facadeModuleId[facadeModuleId.length - 2] || "[name]";
            return `js/${fileName}/[name].[hash].js`;
          },
        },
      },
    },
    server: {
      https: false,
      open: false,
      cors: true,
      port: 3001,
      host: "0.0.0.0",
      proxy: {
        "/cloudrenderingcontrol": {
          target: "http://10.168.1.250:32280",
          changeOrigin: true,
          secure: false,
          ws: true,
          rewrite: (path) =>
            path.replace(/^\/cloudrenderingcontrol/, "/cloudrenderingcontrol"),
        },
        "/api": {
          target: `http://${IP}:3001`,
          changeOrigin: true,
          secure: false,
          ws: false,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
    optimizeDeps: {
      include: [],
    },
    plugins: [
      vue(),
      Inspector(),
      vueJsx(),
      AutoImport({
        // 自动导入 Element Plus 相关函数，如：ElMessage,ElMessageBox...(带样式)
        resolvers: [
          ElementPlusResolver({
            importStyle: "sass",
          }),
          // 自动导入图标组件
          IconsResolver({
            prefix: "Icon",
          }),
        ],
      }),
      Components({
        // 自动导入 Element Plus组件
        resolvers: [
          ElementPlusResolver({
            importStyle: "sass",
          }),
          IconsResolver({
            enabledCollections: ["ep"], // 重点
          }),
        ],
      }),

      Icons({
        autoInstall: true,
      }),
      // 手动导入组件 例如： import { ElButton } from 'element-plus'
      ElementPlus({
        useSource: true,
      }),
      svgBuilder("./src/assets/icons/svg/"),
    ],
  });
};
